#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "error.hpp"

class tcpClient
{
public:
    tcpClient(std::string ip, uint16_t port) : _serverIP(ip), _serverPort(port)
    {
    }
    void init()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            std::cerr << "create socket error" << std::endl;
            exit(SOCKET_ERR);
        }
        // 向服务器发送连接请求
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverPort);
        server.sin_addr.s_addr = inet_addr(_serverIP.c_str());
        // 重连次数
        int cnt = 5;
        while (connect(_sock, (struct sockaddr *)&server, sizeof(server)) != 0)
        {
            std::cout << "正在尝试重连，剩余次数：" << cnt-- << std::endl;
            if (cnt <= 0)
            {
                break;
            }
        }
        if (cnt <= 0)
        {
            std::cerr << "连接失败..." << std::endl;
            exit(CONNECT_ERR);
        }
        // 连接成功了
        std::cout << "conneect success" << std::endl;
    }
    void start()
    {
        char buffer[1024];
        while (true)
        {
            std::string message;
            std::cout << "请输入发送给服务端的信息: ";
            getline(std::cin, message);
            ssize_t strSize=send(_sock, message.c_str(), message.size(), 0);
            if (strSize <= 0)
            {
                std::cerr << "send fail " << strerror(errno) << std::endl;
            }
            // 接受服务端传来的消息
            ssize_t n = recv(_sock, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = '\0';
                std::cout << "server message :" << buffer << std::endl;
            }
            else if (n == 0)
            {
                std::cerr << "server quit" << std::endl;
                break;
            }
            else
            {
                std::cerr << "recv error: " << strerror(errno) << std::endl;
                break;
            }
        }
    }

    ~tcpClient()
    {
        close(_sock);
    }

private:
    int _sock;
    std::string _serverIP;
    uint16_t _serverPort;
};
